import re

from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response

from goods.models import SKU
from users.models import User
from utils.cart import merge_cookie_to_redis

"""
一．确定需求
二．将需求拆分为步骤
三．确定请求方式和url
四．确定视图，实现代码


当光标移开的时候会发送一个ajax请求，这时会携带注册时的用户名

1.接收参数
2.判断该用户名是否已注册
3.返回响应

urls     users/usernames/(?P<username>\w{5,20})/count/
"""
# APIView
# GenericAPIView   列表，视图做了通用支持，一般和MiXin配合使用
# ListAPIView     RetrieveAPIView

# 用户名

from rest_framework.views import APIView
class RegisterUsernameView(APIView):
    def get(self,request,username):
        # 1.接收参数
        # 2.判断该用户名是否已注册
        # 查询用户名，根据返回的count判断
        # count = 0 没有注册
        # count = 1  已经注册

        count = User.objects.filter(username = username).count()

        # 3.返回响应
        return Response({'count':count,'username':username})

# 手机号
"""
当光标离开的时候会向后台发送一个ajax请求

1.接受参数
2.判断该手机号是否已经注册
3.返回响应

url     /users/phones/(?P<mobile>1[345789]\d{9})/count/

"""
from rest_framework.views import APIView

class RegisterPhoneCountAPIView(APIView):

    def get(self,request,mobile):
        # 1.接受参数
        # 2.判断该手机号是否已经注册
        count = User.objects.filter(mobile = mobile).count()

        # 3.返回响应
        return Response({'count':count,'phone':mobile})


"""
用户点击注册按钮的时候，前端需要将6个参数(mobile,password,password2 username,sms_code,allow)
传递给后端

1.接到参数
2.校验参数
3.数据入库
4.返回响应

POST    /users/

"""

from .serializer import RegisterCreateUserSerializer
class RegisterCreateUserView(APIView):

    def post(self,request):
        # 1.接到参数
        data = request.data
        # 2.校验参数
        serializer = RegisterCreateUserSerializer(data=data)
        serializer.is_valid(raise_exception= True)
        # 3.数据入库
        serializer.save()
        # 4.返回响应
        return Response(serializer.data)

"""
让用户注册完成后自动登录，返回一个token

1,在注册成功之后返回token
2,token没有，不知道怎么生成

"""

from rest_framework.permissions import IsAuthenticated
from .serializer import UserCenterInfoSerializer


# 第一种方式
# class UserCenterInfoView(APIView):
#     # １.这个接口只能登录用户访问
#     permission_classes = [IsAuthenticated]
#
#     def get(self, request):
#         # 2.获取登录用户的信息
#         user = request.user
#
#         # 3.创建序列化器
#         serializer = UserCenterInfoSerializer(user)
#
#         # 4.返回数据
#         return Response(serializer.data)


# 第二种方式
from rest_framework.generics import RetrieveAPIView
class UserCenterInfoView(RetrieveAPIView):
    serializer_class = UserCenterInfoSerializer

    #权限
    permission_classes = [IsAuthenticated]

    #重写 get_object()
    def get_object(self):

        return self.request.user

# 邮件保存信息第一种方式
from .serializer import UserUpdateEmailSerializer
# class UserUpdateEmailView(APIView):
#     def put(self,request):
#         #1.接收数据
#         data = request.data
#         user = request.user
#
#         #2.对数据进行校验
#         serializer = UserUpdateEmailSerializer(instance=user,data = data)
#         serializer.is_valid(raise_exception=True)
#
#         #3.更新数据
#         serializer.save()
#         #4.发送激活邮件
#         #5.返回响应
#         return Response(serializer.data)


# 邮件保存信息第二种方式
from rest_framework.generics import UpdateAPIView

class UserUpdateEmailView(UpdateAPIView):
    serializer_class = UserUpdateEmailSerializer

    # queryset = User.objects.all()

    def get_object(self):
        return self.request.user


"""
用户点击激活按钮，跳转到前端页面，前端页面会获取到token
前端获取到token之后，需要将token发送给后端


1.接收token
2.对token进行解密，获取到id
3.根据id获取到user信息
4.修改user的激活状态
5.返回响应
"""

from users.utils import check_active_token
from rest_framework import status
class UserEmailActiveView(APIView):

    def get(self,request):
        # 1.接收token
        token = request.query_params.get('token')
        if token is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 2.对token进行解密，获取到id
        user_id = check_active_token(token)
        if user_id is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 3.根据id获取到user信息
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 4.修改user的激活状态
        user.email_active=True
        user.save()

        # 5.返回响应
        return Response({'msg':'OK'})

from rest_framework.generics import CreateAPIView
from .serializer import AddressSerializer

class AddressView(CreateAPIView):

    serializer_class = AddressSerializer

from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from .serializer import AddressTitleSerializer

class AddressViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,GenericViewSet):
    """
    用户地址新增与修改
    list GET: /users/addresses/
    create POST: /users/addresses/
    destroy DELETE: /users/addresses/
    action PUT: /users/addresses/pk/status/
    action PUT: /users/addresses/pk/title/
    """

    #制定序列化器
    serializer_class = AddressSerializer
    #添加用户权限
    permission_classes = [IsAuthenticated]
    #由于用户的地址有存在删除的状态,所以我们需要对数据进行筛选
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        count = request.user.addresses.count()
        if count >= 20:
            return Response({'message':'保存地址数量已经达到上限'},status=status.HTTP_400_BAD_REQUEST)

        return super().create(request,*args,**kwargs)

    def list(self, request, *args, **kwargs):
        """
        获取用户地址列表
        """
        # 获取所有地址
        queryset = self.get_queryset()
        # 创建序列化器
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        # 响应
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)



"""
添加浏览记录 POST     users/browerhistories/

当用户点击商品详情叶的时候，前端应该发送一个ajax请求给后端，包含sku_id,count,token

1.接受参数，校验参数
2.保存数据
3.返回响应

"""
from django_redis import get_redis_connection
from .serializer import UserHistorySerializer,SKUSerializer
class UserHistoryView(APIView):
    #加权限只能登录用户访问
    permission_classes = [IsAuthenticated]

    def post(self,request):
        user = request.user
        # 1.接受参数，校验参数
        serializer = UserHistorySerializer(data=request.data)

        serializer.is_valid(raise_exception=True)
        # 2.保存数据
        sku_id = serializer.validated_data.get('sku_id')

        #连接数据库
        redis_conn = get_redis_connection('history')

        #先全部删除
        redis_conn.lrem('history_%s'%user.id,0,sku_id)

        #写入redis的列表中
        redis_conn.lpush('history_%s'%user.id,sku_id)

        #对数据进行裁剪
        redis_conn.ltrim('history_%s'%user.id,0,4)

        # 3.返回响应
        return Response(serializer.data)

    """
    获取浏览记录
    1.登录用户访问
    2.从redis 中获取　redis
    3.根据id 获取商品的详细信息
    4.返回响应

    """
    def get(self,request):
        # 1.登录用户访问
        user = request.user
        # 2.从redis 中获取　redis
        #2.1连接redis
        redis_conn = get_redis_connection('history')

        sku_ids = redis_conn.lrange('history_%s'%user.id,0,5)
        # 3.根据id 获取商品的详细信息
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(pk=sku_id)
            skus.append(sku)

        serializer = SKUSerializer(sku,many=True)
        # 4.返回响应
        return Response(serializer.data)




from rest_framework_jwt.views import ObtainJSONWebToken


class UserAuthorizationView(ObtainJSONWebToken):

    def post(self, request):
        # 调用jwt扩展的方法，对用户登录的数据进行验证
        response = super().post(request)

        # 如果用户登录成功，进行购物车数据合并
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 表示用户登录成功
            user = serializer.validated_data.get("user")
            # 合并购物车
            #merge_cart_cookie_to_redis(request, user, response)
            response = merge_cookie_to_redis(request, user, response)

        return response

































